package com.filldream.fastboot.common.okutil.stock.ths.comment;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.filldream.fastboot.common.okutil.stock.cf.comment.dto.CfComment;
import com.filldream.fastboot.common.okutil.stock.ths.comment.dto.ThsComment;
import com.filldream.fastboot.common.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class ThsCommentUtil {

    /**
     * 获取评论
     * @param code
     * @return
     */
    public static List<ThsComment> getComments(final String code) {
        List<ThsComment> resultList = new ArrayList<>();
        //1、处理股票代码
        final String simpleCode = code.substring(2);
        try {
            String httpResult = HttpUtil.get("https://t.10jqka.com.cn/lgt/post/open/api/forum/post/recent/compatibility?page=1&page_size="+RandomUtil.randomInt(15,30)+"&from_id=0"
                    + "&code=" + simpleCode
                    +"&rrr=" + RandomUtil.randomInt(10, 999));
            JSONObject jsonObject = JSONObject.parseObject(httpResult);
            String listJson = jsonObject.getJSONObject("data").getJSONArray("feed").toJSONString();
            resultList = JsonUtil.fromJosnArray(listJson, ThsComment.class);
            resultList = resultList.stream()
                    .sorted(Comparator.comparing(ThsComment::getCtime))
                    .collect(Collectors.toList());
            resultList.forEach( t -> {
                t.setSimpleCode(simpleCode);
                t.setSearchCode(code);
            });
        }catch (Exception e){
            log.error( "请求同花顺论股失败",e );
        }
        return resultList;
    }

    public static List<CfComment> getComments2(String code) {
        List<ThsComment> comments = getComments(code);
        return comments.stream().map(ThsComment::toCfComment).collect(Collectors.toList());
    }

}
